#include "dataqueue.h"
#include "../utils/logger.h"
#include <QDebug>

DataQueue::DataQueue(DBManager *dbManager, QObject *parent)
    : QObject(parent), m_dbManager(dbManager), m_autoFlush(false), m_maxQueueSize(10000), m_totalCached(0)
{
    m_autoFlushTimer = new QTimer(this);
    m_autoFlushTimer->setSingleShot(false);
    connect(m_autoFlushTimer, &QTimer::timeout, this, &DataQueue::onAutoFlush);

    LOG_INFO("数据队列初始化完成");
}

DataQueue::~DataQueue()
{
    stopAutoFlush();

    // 确保所有数据都已写入数据库
    if (!m_dataQueue.isEmpty())
    {
        LOG_INFO(QString("析构时刷新队列，剩余 %1 条数据").arg(m_dataQueue.size()));
        flush();
    }
}

void DataQueue::enqueue(const HistoryData &data)
{
    QMutexLocker locker(&m_queueMutex);

    m_dataQueue.enqueue(data);
    m_totalCached++;

    emit queueSizeChanged();
    emit totalCachedChanged();

    // 检查队列是否满
    if (m_dataQueue.size() >= m_maxQueueSize)
    {
        LOG_WARNING(QString("队列已满 (%1 条)，触发自动刷新").arg(m_dataQueue.size()));
        emit queueFull();

        // 解锁后刷新（避免死锁）
        locker.unlock();
        flush();
    }
}

void DataQueue::enqueueBatch(const QVector<HistoryData> &dataList)
{
    QMutexLocker locker(&m_queueMutex);

    for (const HistoryData &data : dataList)
    {
        m_dataQueue.enqueue(data);
        m_totalCached++;
    }

    emit queueSizeChanged();
    emit totalCachedChanged();

    // 检查队列是否满
    if (m_dataQueue.size() >= m_maxQueueSize)
    {
        LOG_WARNING(QString("队列已满 (%1 条)，触发自动刷新").arg(m_dataQueue.size()));
        emit queueFull();

        locker.unlock();
        flush();
    }
}

int DataQueue::flush()
{
    QMutexLocker locker(&m_queueMutex);

    if (m_dataQueue.isEmpty())
    {
        return 0;
    }

    if (!m_dbManager || !m_dbManager->isConnected())
    {
        LOG_ERROR("数据库未连接，无法刷新队列");
        return 0;
    }

    // 将队列数据转为Vector
    QVector<HistoryData> dataList;
    while (!m_dataQueue.isEmpty())
    {
        dataList.append(m_dataQueue.dequeue());
    }

    // 解锁后写入数据库（避免长时间锁定）
    locker.unlock();

    LOG_INFO(QString("开始刷新队列，共 %1 条数据").arg(dataList.size()));

    int successCount = m_dbManager->batchInsertHistoryData(dataList);

    LOG_INFO(QString("队列刷新完成，成功写入 %1 条数据").arg(successCount));

    emit dataFlushed(successCount);
    emit queueSizeChanged();

    return successCount;
}

void DataQueue::clear()
{
    QMutexLocker locker(&m_queueMutex);
    m_dataQueue.clear();
    emit queueSizeChanged();
    LOG_INFO("队列已清空");
}

void DataQueue::startAutoFlush(int intervalMs)
{
    if (m_autoFlush)
    {
        LOG_WARNING("自动刷新已启动");
        return;
    }

    m_autoFlushTimer->setInterval(intervalMs);
    m_autoFlushTimer->start();
    m_autoFlush = true;

    LOG_INFO(QString("启动自动刷新，间隔: %1 秒").arg(intervalMs / 1000));
    emit autoFlushChanged();
}

void DataQueue::stopAutoFlush()
{
    if (!m_autoFlush)
    {
        return;
    }

    m_autoFlushTimer->stop();
    m_autoFlush = false;

    LOG_INFO("停止自动刷新");
    emit autoFlushChanged();
}

void DataQueue::setAutoFlush(bool enable)
{
    if (enable)
    {
        startAutoFlush();
    }
    else
    {
        stopAutoFlush();
    }
}

void DataQueue::onAutoFlush()
{
    LOG_DEBUG("触发自动刷新");
    flush();
}
